package com.yiwei.zhh.activity;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.zhh.R;
import com.yiwei.zhh.api.callback.ChsiForgetContract;
import com.yiwei.zhh.api.requestInfo.ChsiForgetPwdRequest;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.model.ChsiModel;
import com.yiwei.zhh.model.ChsiPwdModel;
import com.yiwei.zhh.util.ImageUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.view.CircularProgress;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 学信网忘记密码界面
 * Created by Master.Dong on 16/4/10.
 */
public class ChsiForgetPwdActivity extends BaseActivity implements View.OnClickListener, ChsiForgetContract.View {

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CircularProgress loading;
    private Bitmap bitmap;
    private CheckBox mSeeBtn;
    private ImageView mIv, cvImgCode, pvImgCode, icon;
    private RelativeLayout rPhoneView, rEmailView;
    private LinearLayout resultView, inputView, codeView, typeView, emailView, phoneView, pwdView;
    private TextView okBtn, cvBtn, evBtn, pvNextBtn, pvOkBtn, rTitle, rText, tvPhone, tvEmail, pvTishi, pvCodeBtn, findByPhone, findByEmail;
    private EditText cvAccount, cvCode, evEmail, evRealName, evIdno, pvPhone, pvRealName, pvIdno, pvCode, pvCode2, pvPwd;
    private int viewIndex = 1;  //返回按钮判断
    private String ctoken, clst, mobile, email;
    private CheckBox cb;
    private ChsiForgetPwdRequest api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.chsi_pwd_activity);
        baseInitView(this, "ChsiForgetPwdActivity", Const.ViewType.ACTIVITY);
        initView();

    }

    private void initView() {
        api = ChsiForgetPwdRequest.create();
        api.attachView(this);
        setTitleText(getString(R.string.find_password));
        getLeftImgBtn().setOnClickListener(this);

        icon = (ImageView) findViewById(R.id.result_icon);
        cvImgCode = (ImageView) findViewById(R.id.code_v_img_code);
        pvImgCode = (ImageView) findViewById(R.id.phone_v_img_code);
//        icon = (ImageView) findViewById(R.id.result_icon);
        mIv = (ImageView) findViewById(R.id.chsi_iv);
        bitmap = ImageUtil.readBitMap(this, R.mipmap.chsi);
        mIv.setImageBitmap(bitmap);
        mSeeBtn = (CheckBox) findViewById(R.id.see);
        loading = (CircularProgress) findViewById(R.id.progressBar);
        rTitle = (TextView) findViewById(R.id.result_title);
        rText = (TextView) findViewById(R.id.result_text);
        okBtn = (TextView) findViewById(R.id.ok);
        cvBtn = (TextView) findViewById(R.id.code_v_btn);
        evBtn = (TextView) findViewById(R.id.email_v_btn);
        pvNextBtn = (TextView) findViewById(R.id.phone_v_btn);
        pvOkBtn = (TextView) findViewById(R.id.pwd_v_btn);
        tvPhone = (TextView) findViewById(R.id.type_v_phone);
        tvEmail = (TextView) findViewById(R.id.type_v_email);
        pvTishi = (TextView) findViewById(R.id.pwd_v_tishi);
        pvCodeBtn = (TextView) findViewById(R.id.pwd_v_code_btn);
        findByPhone = (TextView) findViewById(R.id.find_by_phone);
        findByEmail = (TextView) findViewById(R.id.find_by_email);


        rPhoneView = (RelativeLayout) findViewById(R.id.type_v_phone_view);
        rEmailView = (RelativeLayout) findViewById(R.id.type_v_email_view);

        inputView = (LinearLayout) findViewById(R.id.input_view);
        resultView = (LinearLayout) findViewById(R.id.result_view);
        codeView = (LinearLayout) findViewById(R.id.code_view);
        typeView = (LinearLayout) findViewById(R.id.type_view);
        emailView = (LinearLayout) findViewById(R.id.email_view);
        phoneView = (LinearLayout) findViewById(R.id.phone_view);
        pwdView = (LinearLayout) findViewById(R.id.pwd_view);

        cvAccount = (EditText) findViewById(R.id.code_v_account);
        cvCode = (EditText) findViewById(R.id.code_v_code);
        evEmail = (EditText) findViewById(R.id.email_v_email);
        evRealName = (EditText) findViewById(R.id.email_v_realname);
        evIdno = (EditText) findViewById(R.id.email_v_idno);
        pvPhone = (EditText) findViewById(R.id.phone_v_phone);
        pvRealName = (EditText) findViewById(R.id.phone_v_realname);
        pvIdno = (EditText) findViewById(R.id.phone_v_idno);
        pvCode = (EditText) findViewById(R.id.phone_v_code);
        pvCode2 = (EditText) findViewById(R.id.pwd_v_code);
        pvPwd = (EditText) findViewById(R.id.pwd_v_new_pwd);
        cb = (CheckBox) findViewById(R.id.cb);

        findByPhone.setOnClickListener(this);
        findByEmail.setOnClickListener(this);
        rPhoneView.setOnClickListener(this);
        rEmailView.setOnClickListener(this);
        cvImgCode.setOnClickListener(this);
        pvImgCode.setOnClickListener(this);
        cvBtn.setOnClickListener(this);
        evBtn.setOnClickListener(this);
        pvNextBtn.setOnClickListener(this);
        pvOkBtn.setOnClickListener(this);
        okBtn.setOnClickListener(this);
        pvCodeBtn.setOnClickListener(this);

        mSeeBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mSeeBtn.setBackgroundResource(R.mipmap.see_off);
                    pvPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); //显示密码
                } else {
                    mSeeBtn.setBackgroundResource(R.mipmap.see);
                    pvPwd.setTransformationMethod(PasswordTransformationMethod.getInstance()); //隐藏密码
                }
                pvPwd.setSelection(pvPwd.getText().length());
            }
        });

        pvTishi.setText(getString(R.string.send_code_to_your_phone) + tvPhone.getText());

        getChsiCode(0);
    }

    private void jumpView() {
        if (viewIndex == 2) showView(1);
        else if (viewIndex == 3) showView(2);
        else if (viewIndex == 4) showView(2);
        else if (viewIndex == 5) showView(4);
        else if (viewIndex == 0) {
            inputView.setVisibility(View.VISIBLE);
            resultView.setVisibility(View.GONE);
            viewIndex = 1;
        } else
            ChsiForgetPwdActivity.this.finish();
    }

    /**
     * 验证码计时器
     */
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            pvCodeBtn.setEnabled(false);
            pvCodeBtn.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
            pvCodeBtn.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        pvCodeBtn.setEnabled(true);
        pvCodeBtn.setText(getResources().getString(R.string.get_code));
        pvCodeBtn.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }

    /**
     * 监听Back按钮
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            jumpView();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                jumpView();
                break;
            case R.id.ok:
                if (viewIndex == 0) {
                    inputView.setVisibility(View.VISIBLE);
                    resultView.setVisibility(View.GONE);
                } else
                    ChsiForgetPwdActivity.this.finish();
                break;
            case R.id.code_v_btn: //验证码界面按钮
                if (codeViewInputCheck())
                    getPwdTypeInfo();
                break;
            case R.id.email_v_btn:
                if (emailViewInputCheck())
                    getPwdByEmail();
                break;
            case R.id.phone_v_btn:
                if (phoneViewInputCheck())
                    getPwdByPhone();
                break;
            case R.id.pwd_v_btn:
                if (phoneViewInputCheck2())
                    getPwdByPhone2();
                break;
            case R.id.code_v_img_code:
                getChsiCode(0);
                break;
            case R.id.phone_v_img_code:
                getChsiCode(1);
                break;
            case R.id.type_v_phone_view:
                showView(4);
                break;
            case R.id.type_v_email_view:
                showView(3);
                break;
            case R.id.find_by_phone:
                showView(4);
                break;
            case R.id.find_by_email:
                showView(3);
                break;
            case R.id.pwd_v_code_btn:
                pvCode.setText("");
                pvCode2.setText("");
                pvPwd.setText("");
                showView(4);
                getChsiCode(1);
                break;
        }
    }

    /**
     * 验证码界面非空判断
     *
     * @return
     */
    private boolean codeViewInputCheck() {
        if (TextUtils.isEmpty(cvAccount.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.account_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(cvCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 安全邮箱界面非空判断
     *
     * @return
     */
    private boolean emailViewInputCheck() {
        if (TextUtils.isEmpty(evEmail.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.email_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(evRealName.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.realname_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(evIdno.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.idcard_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 手机界面非空判断
     *
     * @return
     */
    private boolean phoneViewInputCheck() {
        if (TextUtils.isEmpty(pvPhone.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.phone_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(pvRealName.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.realname_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(pvIdno.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.idcard_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(pvCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 手机界面非空判断
     *
     * @return
     */
    private boolean phoneViewInputCheck2() {
        if (TextUtils.isEmpty(pvCode2.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(pvPwd.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.password_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        api.detachView();
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
        ImageUtil.releaseImageViewResouce(mIv);
    }

    /**
     * 显示的界面
     *
     * @param index
     */
    private void showView(int index) {
        // codeView, typeView, emailView, phoneView, pwdView;
        viewIndex = index;
        if (TextUtils.isEmpty(mobile)) findByPhone.setVisibility(View.INVISIBLE);
        if (TextUtils.isEmpty(email)) findByEmail.setVisibility(View.INVISIBLE);

        codeView.setVisibility(View.GONE);
        typeView.setVisibility(View.GONE);
        emailView.setVisibility(View.GONE);
        phoneView.setVisibility(View.GONE);
        pwdView.setVisibility(View.GONE);

        if (index == 1) codeView.setVisibility(View.VISIBLE);
        if (index == 2) typeView.setVisibility(View.VISIBLE);
        if (index == 3) emailView.setVisibility(View.VISIBLE);
        if (index == 4) phoneView.setVisibility(View.VISIBLE);
        if (index == 5) pwdView.setVisibility(View.VISIBLE);
    }

    private void showResultView(boolean bool, String title, String text) {
        if (bool) {
            viewIndex = 100;
            icon.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.check));
        } else {
            viewIndex = 0;
            icon.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.fall));
        }

        rTitle.setText(title);
        rText.setText(text);
        inputView.setVisibility(View.GONE);
        resultView.setVisibility(View.VISIBLE);
    }

    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (b) {
            cvBtn.setEnabled(false);
            findByPhone.setEnabled(false);
            findByEmail.setEnabled(false);
            rPhoneView.setEnabled(false);
            rEmailView.setEnabled(false);
            evBtn.setEnabled(false);
            pvNextBtn.setEnabled(false);
            pvOkBtn.setEnabled(false);
            okBtn.setEnabled(false);
            pvCodeBtn.setEnabled(false);

            if (loading != null) loading.setVisibility(View.VISIBLE);
        } else {
            cvBtn.setEnabled(true);
            findByPhone.setEnabled(true);
            findByEmail.setEnabled(true);
            rPhoneView.setEnabled(true);
            rEmailView.setEnabled(true);
            evBtn.setEnabled(true);
            pvNextBtn.setEnabled(true);
            pvOkBtn.setEnabled(true);
            okBtn.setEnabled(true);
            pvCodeBtn.setEnabled(true);

            if (loading != null) loading.setVisibility(View.GONE);
        }
    }

    /**
     * 获取学信网图形验证码
     */
    private void getChsiCode(final int type) {
        cvCode.setText("");
        api.getChsiImgCodeInfo(false, type);
    }

    /**
     * 找回密码方式
     */
    private void getPwdTypeInfo() {
        try {
            api.getChsiPwdTypeInfo(URLEncoder.encode(cvAccount.getText().toString(), "UTF-8"), URLEncoder.encode(cvCode.getText().toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过email找回密码
     */
    private void getPwdByEmail() {
        try {
            api.getRetrieveByEmailInfo(ctoken, evEmail.getText().toString(), URLEncoder.encode(evRealName.getText().toString(), "UTF-8"), evIdno.getText().toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过手机找回密码
     */
    private void getPwdByPhone() {
        try {
            api.getRetrieveByPhoneInfo(ctoken, pvPhone.getText().toString(), URLEncoder.encode(pvRealName.getText().toString(), "UTF-8"), pvIdno.getText().toString(), URLEncoder.encode(pvCode.getText().toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过手机找回密码
     */
    private void getPwdByPhone2() {
        api.getRetrieveByPhoneInfo2(clst, pvCode2.getText().toString(), pvPwd.getText().toString());
    }


    @Override
    public void showError() {
        pvPwd.setText("");
    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    @Override
    public void getChsiImgCodeInfoSuccess(int type, ChsiModel model) {
        String imgStr = "";
        String captcha = model.data.getCaptcha();
        if (captcha.contains(",")) {
            imgStr = captcha.substring(captcha.indexOf(',') + 1);
            if (type == 0)
                cvImgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
            if (type == 1) pvImgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));

        } else cvImgCode.setImageDrawable(null);
    }

    @Override
    public void getChsiPwdTypeInfoSuccess(ChsiPwdModel model) {
        ctoken = model.getCtoken();
        mobile = model.getData().getMobile();
        email = model.getData().getEmail();
        if (model.getStatus() == 1) {
            if (!TextUtils.isEmpty(mobile)) {
                tvPhone.setText(model.getData().getMobile());
                rPhoneView.setVisibility(View.VISIBLE);
                getChsiCode(1);
            }
            if (!TextUtils.isEmpty(email)) {
                tvEmail.setText(model.getData().getEmail());
                rEmailView.setVisibility(View.VISIBLE);
                evEmail.setText(email);
            }

            showView(2);
        } else {
            cvCode.setText("");
            if (model.getMsg().contains(getString(R.string.code)))
                ToastUtil.makeText(getApplicationContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
            else showResultView(false, getString(R.string.find_fail), model.getMsg());
            getChsiCode(0);
        }
    }

    @Override
    public void getRetrieveByEmailInfoSuccess(ChsiModel model) {
        if (model.getStatus() == 1) {
            showResultView(true, model.getMsg(), model.data.getDescription());
        } else if (model.getStatus() == 0) {
            showResultView(false, model.getMsg(), model.data.getDescription());
        }
        ToastUtil.makeText(getApplicationContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getRetrieveByPhoneInfoSuccess(ChsiModel model) {
        if (model.getStatus() == 1) {
            clst = model.data.getClst();
            timer.start();
            showView(5);
        } else if (model.getStatus() == 0) {
            pvCode.setText("");
            ToastUtil.makeText(getApplicationContext(), model.data.getDescription(), Toast.LENGTH_SHORT).show();
            getChsiCode(1);
        }
    }

    @Override
    public void getRetrieveByPhoneInfo2Success(ChsiModel model) {
        showResultView(true, model.getMsg(), model.data.getDescription());
    }
}
